<?php

namespace app\common\model\mycurrency;

use think\Exception;
use think\Model;
use think\Queue;
use traits\model\SoftDelete;

class LeaseOrderPay extends Model
{

    //use SoftDelete;

    // 表名
    protected $name = 'mycurrency_lease_order_pay';

    // 追加属性
    protected $append = [];

    const PAY_STATUS__QUXIAO = -1;//支付状态:-1=取消支付
    const PAY_STATUS__DAIZHIFU = 1;//支付状态:1=待支付
    const PAY_STATUS__ZHIFUZHONG = 2;//支付状态:2=支付中
    const PAY_STATUS__YIZHIFU = 3;//支付状态:3=已支付
    const PAY_STATUS_TUIKUANZHONG = 4;//支付状态:4=退款中
    const PAY_STATUS_YITUIKUAN = 5;//支付状态:5=已退款

    const PAY_OPPORTUNITY_SHIYONGQIAN = 1;//支付时机:1=使用前支付
    const PAY_OPPORTUNITY_SHIYONGHOU = 2;//支付时机:2=用完后支付

    const PAY_TYPE_WECHAT             = 1;//支付类型 = 微信支付
    const PAY_TYPE_ALIPAY             = 2;//支付类型 = 支付宝支付
    const PAY_TYPE_YUE                = 3;//支付类型 = 余额
    const PAY_TYPE_MIANYA             = 4;//支付类型 = 免押
    const PAY_TYPE_YAJINDIKOU         = 5;//支付类型 = 押金抵扣

    //生成代理商唯一编号
    public static function getSn(){
        $number = date('YmdHis') . mt_rand(1000, 9999);
        $exists = self::where('sn', $number)->value('id');
        if (!$exists) {
            return $number;
        }
        return self::getSn();
    }


    /**
     * 创建支付记录
     * @param int $order_id 订单id
     * @param int $pay_opportunity 支付时机:1=使用前支付,2=用完支付
    */
    public static function payAdd($order_id,$pay_opportunity){
        //订单信息
        $order = LeaseOrder::get($order_id);
        if (!$order){
            throw new Exception('订单不存在');
            return false;
        }
        //租赁费用
        $amount = 0;//需要支付金额
        if ($pay_opportunity == self::PAY_OPPORTUNITY_SHIYONGQIAN){//使用前支付
            if ($order['strategy_types'] == LeaseOrder::STRATEGY_TYPES_SHICHANG){//1=按时长计费
                throw new Exception('按使用时长计费无法先支付');
                return false;
            }elseif ($order['strategy_types'] == LeaseOrder::STRATEGY_TYPES_CISHU){//2=按次数计费
                $amount = $order->rent_fee;
            }elseif ($order['strategy_types'] == LeaseOrder::STRATEGY_TYPES_TAOCAN){//3=按套餐计费
                $amount = $order->rent_fee;
            }
        }elseif ($pay_opportunity == self::PAY_OPPORTUNITY_SHIYONGHOU){//用完后支付
            $amount = $order->pending_payment;
        }

        $increase = [
            'sn' => self::getSn(),
            'lease_order_id' => $order->id,
            'user_id' => $order->user_id,
            'money' => $amount,
            'pay_status' => self::PAY_STATUS__DAIZHIFU,
            'createtime' => time(),
            'pay_opportunity' => $pay_opportunity,
        ];
        $pay = self::create($increase);

        //添加定时任务
//        $queue_default = config('queue.default');
//        Queue::later(300, "addons\mycurrency\controller\job\Lease@payPaymentVerification", ['pay_id' => $pay['id']], $queue_default);

        return $pay;
    }

    /**
     * 支付成功
     * @param int $order_pay_id 租赁订单支付记录id
     * @param int $pay_type 支付类型
    */
    public static function paySuccess($order_pay_id,$pay_type){
        $order_pay = self::get($order_pay_id);
        if(!$order_pay){
            throw new Exception('支付记录不存在');
            return false;
        }
        if($order_pay['pay_status'] != self::PAY_STATUS__DAIZHIFU){
            throw new Exception('非待支付状态');
            return false;
        }
        trace(["28========================处理lease_order_id报错问题_paySuccess==============================" => $order_pay],'error');
        $order = LeaseOrder::get($order_pay['lease_order_id']);

        //修改支付订单状态
        $order_pay->pay_status = self::PAY_STATUS__YIZHIFU;
        $order_pay->pay_type = $pay_type;
        $order_pay->payment_time = time();
        $order_pay->save();

        //处理主订单逻辑
        if($order_pay->pay_opportunity == self::PAY_OPPORTUNITY_SHIYONGQIAN){//先付后租 支付成功后逻辑处理
            //修改主订单
            $order->use_status = LeaseOrder::USE_STATUS_JINXINGZHONG;
            $order->paid_dlready += $order_pay->money;
            $order->pending_payment -= $order_pay->money;
            $order->save();
            //开始租赁设备
            trace(["29========================处理lease_order_id报错问题_paySuccess 1==============================" => $order_pay],'error');
            LeaseOrder::orderStartRenting($order_pay['lease_order_id']);
        }elseif ($order_pay->pay_opportunity == self::PAY_OPPORTUNITY_SHIYONGHOU){//先租后付款 支付成功后逻辑处理
            $order->paid_dlready += $order_pay->money;
            $order->pending_payment -= $order_pay->money;
            if($order->pending_payment <= 0){
                $order->use_status = LeaseOrder::USE_STATUS_YIWANCHENG;
            }
            $order->save();

            LeaseOrder::orderDivideinto($order->id);
        }

    }


    /**
     * 支付退款
     * @param int $order_pay_id 租赁订单支付记录id
    */
    public static function payRefund($order_pay_id){
        $pay = self::where(['id' => $order_pay_id,'deletetime' => null])->find();
        if(!$pay){
            throw new Exception('支付记录不存在');
            return false;
        }
        if($pay['pay_status'] != self::PAY_STATUS__YIZHIFU){
            throw new Exception('非已支付状态');
            return false;
        }
        $pay->pay_status = self::PAY_STATUS_TUIKUANZHONG;
        $pay->refund_time = time();
        $pay->save();

        //根据支付方式原路退回押金
        if($pay->pay_type == self::PAY_TYPE_WECHAT || $pay->pay_type == self::PAY_TYPE_ALIPAY) {//支付方式 ：  微信or支付宝 yss临时 未实现

        }elseif($pay->pay_type == self::PAY_TYPE_MIANYA){//支付方式 ： 免押

        }elseif ($pay->pay_type == self::PAY_TYPE_YUE){//支付方式 ： 余额支付
            //扣除用户余额
            UserMoneyLog::moneyChange($pay['user_id'],$pay['money'],UserMoneyLog::TYPE_ZULINFEIYONGTUIHUEI,[
                'memo' => '押金退回',
                'lease_order_pay_id' => $pay->id,
            ]);
            self::payRefundSuccess($pay->id);
        }
    }

    /**
     * 支付退款成功后逻辑
     * @param int $order_pay_id 租赁订单支付记录id
    */
    public static function payRefundSuccess($order_pay_id){
        $pay = self::where(['id' => $order_pay_id,'deletetime' => null])->find();
        if(!$pay){
            throw new Exception('支付记录不存在');
            return false;
        }
        if($pay['pay_status'] != self::PAY_STATUS_TUIKUANZHONG){
            throw new Exception('非退款中状态');
            return false;
        }
        $pay->pay_status = self::PAY_STATUS_YITUIKUAN;
        $pay->complete_refund_time = time();
        $pay->save();
    }


    /**
     * 租赁订单使用押金抵扣后创建押金支付记录
     * @param int $order_id 订单id
     * @param int $money 支付金额
    */
    public static function leaseDepositDeduction($order_id,$money){
        $order = LeaseOrder::get($order_id);
        $increase = [
            'sn' => self::getSn(),
            'lease_order_id' => $order->id,
            'user_id' => $order->user_id,
            'money' => $money,
            'pay_status' => self::PAY_STATUS__YIZHIFU,
            'pay_type' => self::PAY_TYPE_YAJINDIKOU,
            'launch_time' => time(),
            'payment_time' => time(),
            'createtime' => time(),
            'pay_opportunity' => self::PAY_OPPORTUNITY_SHIYONGHOU,
        ];
        $pay = self::create($increase);
    }

}
